package com.runfast.paotui.task.scheduler;

import com.runfast.paotui.dao.model.Order;
import com.runfast.paotui.dao.model.OrderExample;
import com.runfast.paotui.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author: lijin
 * @date: 2018年04月16日
 */
@Component
@Slf4j
public class OrderScheduler {

    @Autowired
    private OrderService orderService;

    @Scheduled(fixedDelay = 10 * 60 * 1000, initialDelay = 0)
    public void onCanceled() {

        /*OrderExample orderCreatedExample = new OrderExample();
        orderCreatedExample.createCriteria().andStatusEqualTo(Order.Status.CREATED.ordinal());

        Order orderUpdate = new Order();
        orderUpdate.withStatus(Order.Status.CANCELED);
        orderService.updateByExampleSelective(orderUpdate, orderCreatedExample);*/

        OrderExample orderPaidExample = new OrderExample();
        orderPaidExample.or().andStatusEqualTo(Order.Status.CREATED.ordinal());
        orderPaidExample.or().andStatusEqualTo(Order.Status.PAID.ordinal());

        List<Map<String, Integer>> maps = orderService.selectIdUserIdByExample(orderPaidExample);
        for (Map<String, Integer> map : maps) {
            Integer id = map.get("id");
            Integer userId = map.get("userId");

            orderService.cancel(userId, id);
        }


        StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
        log.info("文件名：" + stackTraceElement.getFileName()
                + " 类和方法名：" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName()
                + " 行号：" + stackTraceElement.getLineNumber()
                + " 描述：" + "订单取消");
    }


    @Scheduled(fixedDelay = 24 * 3600 * 1000, initialDelay = 0)
    public void onCompleted() {

        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andStatusEqualTo(Order.Status.TAKEN.ordinal());

        Order orderUpdate = new Order();
        orderUpdate.withStatus(Order.Status.COMPLETED);
        orderService.updateByExampleSelective(orderUpdate, orderExample);

        StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
        log.info("文件名：" + stackTraceElement.getFileName()
                + " 类和方法名：" + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName()
                + " 行号：" + stackTraceElement.getLineNumber()
                + " 描述：" + "订单完成");
    }
}
